package com.yimixian.app.common;

import android.os.Bundle;
import android.text.TextUtils;
import com.yimixian.app.R;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.util.NetworkUtils;
import com.yimixian.app.util.SharedPreferencesHelper;
import com.yimixian.app.util.Strings;
import com.yimixian.app.util.UiUtils;

import org.json.JSONException;
import org.json.JSONObject;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by zhilian-2 on 2015/10/9.
 */
public abstract  class BaseHttpActivity extends YmxTitleBarActivity implements Callback<Response> {

        @Override
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
        }

        public abstract void initRequestAPI(String requestKeys);

        public abstract void onHttpSuccess(String url, JSONObject responseJson);

        public void getRawResponse(String url,Response response){ }

        public abstract void OnHttpFailure(String url, String errorMessage, boolean errorFromUs);

        public abstract void fetchDataFromNetwork(String key);


        /**
         * if need,override this fun,fetch local data from db or file
         *
         * @param key
         * @return
         */
        public String fetchDataFromLocal(String key) {
                return SharedPreferencesHelper.getString(key);
        }


        /**
         * fetch data from local or network
         *
         * @param isFetchFromNetWork
         * @param requestKey
         */
        public void fetchData(boolean isFetchFromNetWork, String requestKey) {
                if (isFetchFromNetWork) {
                        if (checkNetWorkState()) {
                                fetchDataFromNetwork(requestKey);
                        }
                } else {
                        fetchDataFromLocal(requestKey);
                }
        }

        /**
         * check network is avaliable for better battery performance
         *
         * @return
         */
        public boolean checkNetWorkState() {
                if (NetworkUtils.isNetworkAvaliable(SystemFramework.getInstance().getGlobalContext())) {
                        return true;
                } else {
                        UiUtils.showToast(getString(R.string.errcode_network_unavailable));
                        return false;
                }
        }

        /**
         * retrofit sucess
         *
         * @param baseResponse
         * @param response
         */
        @Override
        public void success(Response baseResponse, Response response) {
                String url = response.getUrl();
                String json = "";
                JSONObject jsonObject = null;
                getRawResponse(url,response);
                try {
                        json = Strings.inputStream2String(response.getBody().in());
                } catch (Exception e) {
                        e.printStackTrace();
                        OnHttpFailure(url, SystemFramework.getInstance().getGlobalContext()
                                .getString(R.string.io_error), false);
                        return;
                }

                if (!TextUtils.isEmpty(json)) {
                        try {
                                jsonObject = new JSONObject(json);

                        } catch (JSONException e) {
                                e.printStackTrace();
                                OnHttpFailure(url, SystemFramework.getInstance().getGlobalContext()
                                        .getString(R.string.json_error), false);
                                return;
                        }
                }

                // 返回error信息
                if (jsonObject != null) {
                        JSONObject errorObject = jsonObject.optJSONObject("error");
                        if (errorObject != null) {// 返回错误信息
                                com.yimixian.app.rest.response.Error error = new com.yimixian.app.rest.response.Error();
                                error.code = errorObject.optInt("code");
                                error.message = errorObject.optString("message");
                                if (!TextUtils.isEmpty(error.message)) {
                                        UiUtils.showToast(error.message);
                                        OnHttpFailure(url, error.message, true);
                                        return;
                                }
                        }
                }

                onHttpSuccess(url, jsonObject);
        }

        /**
         * retrofit failure
         *
         * @param error
         */
        @Override
        public void failure(RetrofitError error) {
                UiUtils.showToast(SystemFramework.getInstance().getGlobalContext()
                        .getString(R.string.network_error));
                OnHttpFailure(error.getUrl(), error.getMessage(), false);
        }


}